//
//  NetworkHelper.m
//  APIRequest
//
//  Created by 郑佳 on 2017/8/20.
//  Copyright © 2017年 Frank. All rights reserved.
//

#import "NetworkHelper.h"
#import <AFNetworking/AFNetworking.h>

NSString * const POST = @"POST";
NSString * const GET = @"GET";

@interface NetworkHelper ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

@implementation NetworkHelper

+ (instancetype)sharedInstance {
    
    static NetworkHelper *_instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[NetworkHelper alloc]init];
    });
    return _instance;
}

- (void)requestMethod:(NSString *)method url:(NSString *)url parameters:(id)parameters finishBlock:(void (^)(id, NSError *))finishBlock {
    if ([method isEqualToString:GET]) {
        [self GET:url parameters:parameters finishBlock:finishBlock];
    } else {
        [self POST:url parameters:parameters finishBlock:finishBlock];
    }
}

- (void)GET:(NSString *)URLString parameters:(id)parameters finishBlock:(void (^)(id, NSError *))finishBlock {
    [self.manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        finishBlock(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finishBlock(nil,error);
    }];
}

- (void)POST:(NSString *)URLString parameters:(id)parameters finishBlock:(void (^)(id, NSError *))finishBlock {
    [self.manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        finishBlock(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finishBlock(nil,error);
    }];
}
- (void)requestUploadImagesMethod:(NSArray *)imagesArray urlfileName:(NSString *)urlfileName  url:(NSString *)url parameters:(id)parameters finishBlock:(void (^)(id data, NSError *error))finishBlock{
    // 基于AFN3.0+ 封装的HTPPSession句柄
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 40;
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil]];
    // 在parameters里存放照片以外的对象
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
        for (int i = 0; i < imagesArray.count; i++) {
            UIImage *image = imagesArray[i];
            NSData *data = [self zipNSDataWithImage:image ];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            //            // 设置时间格式
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.png", dateString];
            //            /*
            //             *该方法的参数
            //             1. appendPartWithFileData：要上传的照片[二进制流]
            //             2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
            //             3. fileName：要保存在服务器上的文件名
            //             4. mimeType：上传的文件的类型
            //             */
            
            [formData appendPartWithFileData:data name:urlfileName fileName:fileName mimeType:@"image/jpeg"]; //
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"---上传进度--- %@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        finishBlock(responseObject,nil);
         
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"---上传失败--- %@", error);
        finishBlock(nil,error);
    }];
}
//图片压缩
-(NSData *)zipNSDataWithImage:(UIImage *)sourceImage{
    //进行图像尺寸的压缩
    CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
    CGFloat width = imageSize.width;    //图片宽度
    CGFloat height = imageSize.height;  //图片高度
    //1.宽高大于1280(宽高比不按照2来算，按照1来算)
    if (width>1280) {
        if (width>height) {
            CGFloat scale = width/height;
            height = 1280;
            width = height*scale;
        }else{
            CGFloat scale = height/width;
            width = 1280;
            height = width*scale;
        }
        //2.高度大于1280
    }else if(height>1280){
        CGFloat scale = height/width;
        width = 1280;
        height = width*scale;
    }else{
    }
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    [sourceImage drawInRect:CGRectMake(0,0,width,height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //进行图像的画面质量压缩
    NSData *data=UIImageJPEGRepresentation(newImage, 0.5);
        if (data.length>100*1024) {
            if (data.length>1024*1024) {//1M以及以上
                data=UIImageJPEGRepresentation(newImage, 0.7);
            }else if (data.length>512*1024) {//0.5M-1M
                data=UIImageJPEGRepresentation(newImage, 0.8);
            }else if (data.length>200*1024) {
                //0.25M-0.5M
                data=UIImageJPEGRepresentation(newImage, 0.9);
            }
        }
    return data;
}



- (AFHTTPSessionManager *)manager {
    if (_manager == nil) {
        _manager = [AFHTTPSessionManager manager];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"text/html", @"text/plain", @"text/json", @"text/javascript", @"application/json"]];
        _manager.requestSerializer.timeoutInterval = 15;
    }
    return _manager;
}

@end
